import { extend } from "umi-request";
import { message } from 'antd';
import config from "./config";
import { history } from 'umi';

const request = extend({
  prefix: "",             //前缀
  suffix: "",
  timeout: 1000,
  headers: {
    "Content-Type": "application/json"
  },
  params: {
    token: "xxx" // 所有请求默认带上 token 参数
  },
  errorHandler: function(error) {
    /* 异常处理 */
  }
});
//  get请求拼接提交参数
const assyParams = (obj) => {
  let str = ''
  for (let key in obj) {
    const value = typeof obj[key] !== 'string' ? JSON.stringify(obj[key]) : obj[key]
    str += '&' + key + '=' + value
  }
  return str.substr(1);
}


const setConfig = (obj)=>{

  // 处理token
  if(!localStorage.getItem('token')){
    history.push('/login');
  }

  let umiRequest = null;
  // 配置请求地址
  let url = config.proxy ? obj.url : config.apiUrl + obj.url;
  
  if(obj.method == "GET"){
    umiRequest = request.get(url += ('?'+ assyParams(obj.data)));
  }else if(obj.method == "POST"){
    umiRequest = request.post(url, { data:obj.data })
  }

  return umiRequest.then(function(response) {
    if(response.code != 200){
        message.error(response.msg);
    }
    return response;
  })
  .catch(function(error) {
    console.log(error);
  });
}






export function httpGet(url,data) {
  return setConfig({url,method:'GET',data})
}

export function httpPost(url, data) {
  return setConfig({url,method:'POST',data})
}

 
